# coding:utf-8
# pylint: disable=unused-variable
import time
# pySerial
import serial

from Parser import InputParser


class Communicator:

    def __init__(self, port='COM1', baudrate=4800, encoding='ascii'):
        self.config = {'port': port, 'baudrate': baudrate}
        self.serial = serial.Serial(**self.config)
        self.encoding = encoding
        if not self.serial.is_open:
            try:
                print('Open Serial')
                self.serial.open()
            except serial.SerialException as err:
                print('Error:', err)

    def receive(self, queryInterval=0.5, decode=False):
        while True:
            length = self.serial.in_waiting
            if length != 0:
                data = self.serial.read(length)
                # print('收到数据!')
                break
            else:
                # print('没有数据!')
                time.sleep(queryInterval)
                continue
        if decode:
            try:
                newData = data.decode(self.encoding)
                data = newData
            except Exception as err:
                print('Decodeing Failed, Still Return In Bytes!')
        return data

    def sendStr(self, text: str):
        try:
            data = text.encode(self.encoding)
            ans = self.sendByte(data)
        except Exception as err:
            pass
        return ans

    def sendByte(self, byte: bytes):
        ans = False
        if self.serial.writable:
            try:
                self.serial.write(byte)
                ans = True
            except Exception as err:
                ans = False
        return ans


def test():
    com = Communicator(baudrate=9600, encoding='gbk')
    byte = InputParser.RudderControl(
        12.3, 32.4, checkSum=True, newLine=True, returnAsByte=True)
    while True:
        data = com.receive(decode=True)
        print('收到:', data)
        com.sendByte(byte)


if __name__ == "__main__":
    test()
